package com.techindata.cacheredis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
 * 
 * @author dongbing
 *
 */
@Deprecated
public class CacheHTable {
	static Logger logger = Logger.getLogger(CacheHTable.class.getName());
	private int DBINDEX=1;
	private String ROWKEY_PREFIX="";
	
	/**
	 * 
	 * @param dbindex	选择要操作的库索引（取值范围：0~15，默认为1号库）。
	 * @param rowkey_prefix	行键前缀，用于区分不同的应用,只在构造对象时指定。
	 */
	public CacheHTable(int dbindex,String rowkey_prefix){
		this.DBINDEX=dbindex;
		this.ROWKEY_PREFIX=rowkey_prefix;
	}
	
	
	/**
	 * 判断是否已经存在指定的行键。
	 * @param rowkey
	 * @return
	 */
	public boolean isExists(String rowkey){
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			return jedis.exists(rowkey);
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	/**
	 * 判断是否已经存在指定的行键。
	 * @param rowkey
	 * @return
	 */
	public boolean isExists(String rowkey,String field){
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			return jedis.hexists(rowkey, field);
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	
	/**
	 * 插入一行
	 * @param rowkey	行键
	 * @param field	列名
	 * @param value	值
	 * @return	操作是否成功
	 */
	public boolean putRow(String rowkey,String field,String value,int expireTime){
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			jedis.hset(rowkey, field, value);
            if(expireTime>0){
                jedis.expire(rowkey,expireTime);
            }
			return true;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}

    /**
     * 插入一行
     * @param rowkey	行键
     * @param field	列名
     * @param value	值
     * @return	操作是否成功
     */
    public boolean putRow(String rowkey,String field,byte[] value,int expireTime){
        rowkey=ROWKEY_PREFIX+rowkey;
        JedisPool pool=RedisConnectionPool.getPool();
        Jedis jedis=pool.getResource();
        jedis.select(DBINDEX);
        try{
            jedis.hset(rowkey.getBytes(), field.getBytes(), value);
            if(expireTime>0){
                jedis.expire(rowkey,expireTime);
            }
            return true;
        }
        catch(Exception e){
            logger.error(e.getMessage(),e);
            return false;
        }
        finally{
            RedisConnectionPool.returnResource(pool, jedis);
        }
    }
	
	
	/**
	 * 插入多行
	 * @param rows	Map<行键，Map<列名，值>>
	 * @return	操作是否成功
	 */
	public boolean putRows(Map<String,Map<String,String>> rows,int expireTime){
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			for(String rowkey:rows.keySet()){
				Map<String,String> fvs=rows.get(rowkey);
				rowkey=ROWKEY_PREFIX+rowkey;		
				jedis.hmset(rowkey, fvs);
                if(expireTime>0){
                    jedis.expire(rowkey,expireTime);
                }
			}
			return true;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	/**
	 * 插入一行
	 * @param rowkey	行键
	 * @param increment	列名
	 * @param value	值
	 * @return	操作是否成功
	 */
	public boolean incrBy(String rowkey,String value,long increment){
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			jedis.hincrBy(rowkey, value, increment);
			return true;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	
	/**
	 * 插入多行
	 * @param rows	Map<行键，值>
	 * @return	操作是否成功
	 */
	public boolean incrBy(Map<String,String> rows,long increment){
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			for(String rowkey:rows.keySet()){
				rowkey=ROWKEY_PREFIX+rowkey;
				String value=rows.get(rowkey);
				jedis.hincrBy(rowkey, value, increment);
			}
			return true;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	
	/**
	 * 获取与正则表达式相匹配的行键的集合
	 * @param regex	rowkey正则表达式
	 * @return
	 */
	public Set<String> getRowKeys(String regex){
		regex=ROWKEY_PREFIX+regex;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		Set<String> result=new HashSet<String>();
		try{
			result=jedis.keys(regex);
			return result;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return result;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	/**
	 * 获取列名的集合
	 * @param rowkey 行键
	 * @return	列名集合
	 */
	public Set<String> getFields(String rowkey){ 
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		Set<String> result=new HashSet<String>();
		try{
			result=jedis.hkeys(rowkey);
			return result;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return result;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	/**
	 * 获取行值集合
	 * @param rowkey	行键
	 * @return	行值的集合
	 */
	public List<String> getValues(String rowkey){
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		List<String> result=new ArrayList<String>();
		try{
			//for(String key:jedis.keys(rowkey)){
				result=jedis.hvals(rowkey);
			//}
			return result;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return result;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}




    /**
     * 获取行键值集合
     * @param rowkey	行键
     * @return	行键值的集合
     */
    public Map<String,String> getKeyValues(String rowkey){
        rowkey=ROWKEY_PREFIX+rowkey;
        JedisPool pool=RedisConnectionPool.getPool();
        Jedis jedis=pool.getResource();
        jedis.select(DBINDEX);
        Map<String,String> result=new HashMap<String, String>();
        try{
            //for(String key:jedis.keys(rowkey)){
            result=jedis.hgetAll(rowkey);
            //}
            return result;
        }
        catch(Exception e){
            logger.error(e.getMessage(),e);
            return result;
        }
        finally{
            RedisConnectionPool.returnResource(pool, jedis);
        }
    }
	
	
	public Map<String,String> getValuesByFields(String rowkey,String... fields){
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		Map<String,String> result=new HashMap<String,String>();
		try{
			for(String field:fields){
				//for(String key:jedis.keys(rowkey)){
					result.put(field, jedis.hget(rowkey, field));
				//}
			}
			return result;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return result;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}


    public Map<byte[],byte[]> getByteValuesByFields(String rowkey,String... fields){
        rowkey=ROWKEY_PREFIX+rowkey;
        JedisPool pool=RedisConnectionPool.getPool();
        Jedis jedis=pool.getResource();
        jedis.select(DBINDEX);
        Map<byte[],byte[]> result=new HashMap<byte[],byte[]>();
        try{
            for(String field:fields){
                //for(String key:jedis.keys(rowkey)){
                result.put(field.getBytes(), jedis.hget(rowkey.getBytes(), field.getBytes()));
                //}
            }
            return result;
        }
        catch(Exception e){
            logger.error(e.getMessage(),e);
            return result;
        }
        finally{
            RedisConnectionPool.returnResource(pool, jedis);
        }
    }
	
	/**
	 *获取多行的值集合
	 * @param rowkeys	行键列表
	 * @return	值的集合
	 */
	public Map<String,Map<String,String>> getValuesFromRows(List<String> rowkeys){
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		Map<String,Map<String,String>> result=new HashMap<String, Map<String, String>>();
		try{
			for(String rowkey:rowkeys){
				//for(String key:jedis.keys(rowkey)){
				    rowkey=ROWKEY_PREFIX+rowkey;
                result.put(rowkey,jedis.hgetAll(rowkey));
				//	result.addAll(jedis.hgetAll(rowkey));//.hvals(rowkey));
				//}
			}
			return result;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return result;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	/**
	 * 获取多行的特定列
	 * @param rowkeys	行键集合
	 * @param fields	列名集合
	 * @return	Map<行键，Map<列名，值>>
	 */
	public Map<String,Map<String,String>> getValuesFromRowsByFields(List<String> rowkeys,String... fields){
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		Map<String,Map<String,String>> result=new HashMap<String,Map<String,String>>();
		try{
			for(String rowkey:rowkeys){
				//for(String key:jedis.keys(rowkey)){
					rowkey=ROWKEY_PREFIX+rowkey;
					Map<String,String> fvs=new HashMap<String,String>();
					for(String field:fields){
						fvs.put(field, jedis.hget(rowkey, field));
					}
					result.put(rowkey, fvs);
				//}
			}
			return result;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return result;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	/**
	 * 删除匹配正则的行
	 * @param rowkey	行键正则表达式
	 * @return	操作是否成功
	 */
	public boolean del(String rowkey){
		rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			//for(String key:jedis.keys(rowkey)){
				jedis.del(rowkey);
			//}
			return true;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	
	
	/*
	 * 删除特定行的特定列
	 */
    public boolean del(String rowkey,String... fields){
    	rowkey=ROWKEY_PREFIX+rowkey;
		JedisPool pool=RedisConnectionPool.getPool();
		Jedis jedis=pool.getResource();
		jedis.select(DBINDEX);
		try{
			//for(String key:jedis.keys(rowkey)){
				jedis.hdel(rowkey, fields);
			//}
			return true;
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
    
}
